import Flutter
import UIKit
import Reachability

public class GetNetworkStatePlugin: NSObject, FlutterPlugin, FlutterStreamHandler {
    private var reachability: Reachability!
    private var eventSink: FlutterEventSink?

    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "get_network_state", binaryMessenger: registrar.messenger())
        let instance = GetNetworkStatePlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)

        let eventChannel = FlutterEventChannel(name: "get_network_state_events", binaryMessenger: registrar.messenger())
        eventChannel.setStreamHandler(instance)
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if call.method == "getNetWorkState" {
            let isNetworkAvailable = isNetworkConnected()
            result(isNetworkAvailable)
        } else if call.method == "startMonitoring" {
              startMonitoring()
              result(nil)
      }else if call.method == "init" {
               initialize()
               result(nil)
       } else if call.method == "stopMonitoring" {
            stopMonitoring()
            result(nil)
        } else {
            result(FlutterMethodNotImplemented)
        }
    }
    private func initialize() {
        do {
            reachability = try Reachability()
        } catch {
            print("无法初始化 Reachability: \(error)")
        }
    }
    private func startMonitoring() {
        do {
            try reachability.startNotifier()
            reachability.whenReachable = { reachability in
                self.handleReachabilityChange(reachability)
            }
            reachability.whenUnreachable = { reachability in
                self.handleReachabilityChange(reachability)
            }
        } catch {
            print("无法开始网络监听")
        }
    }

    private func stopMonitoring() {
        reachability.stopNotifier()
        eventSink = nil
    }

    private func isNetworkConnected() -> Bool {
        if let currentReachability = reachability {
            return currentReachability.connection != .unavailable
        }
        return false
    }

    // FlutterStreamHandler methods
    public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        eventSink = events
        return nil
    }

    public func onCancel(withArguments arguments: Any?) -> FlutterError? {
        eventSink = nil
        return nil
    }

    private func handleReachabilityChange(_ reachability: Reachability) {
        let isNetworkAvailable = reachability.connection != .unavailable
        eventSink?(isNetworkAvailable)
    }
}
